package udptest

import (
	"bytes"
	"encoding/json"
	"github.com/iikira/iikira-go-utils/utils/converter"
	"log"
	"net"
	"strconv"
)

func NewServer(listenAddr string) {
	addr, err := net.ResolveUDPAddr("udp", listenAddr)
	checkErr(err)

	conn, err := net.ListenUDP("udp", addr)
	checkErr(err)

	defer conn.Close()

	in := make([]byte, 3)
	randBuf := make([]byte, ContentLength)
	jsonBuf := bytes.NewBuffer(make([]byte, 0, 16*converter.KB))
	encoder := json.NewEncoder(jsonBuf)
	for {
		// Here must use make and give the lenth of buffer
		n, rAddr, err := conn.ReadFromUDP(in)
		if err != nil {
			log.Println(err)
			continue
		}
		log.Printf("ReadFromUDP addr: %s, quote(in): %s", rAddr.String(), strconv.Quote(converter.ToString(in[:n])))

		packageNum, err := strconv.Atoi(converter.ToString(in[:n]))
		if err != nil {
			packageNum = 1
		}

		for i := 0; i < packageNum; i++ {
			RandStringBytesMaskImpr(randBuf)
			// 发送随机大小的data
			encoder.Encode(&Msg{
				Seq:   i,
				SrcIp: rAddr.String(),
				Data:  converter.ToString(randBuf[:r.Intn(int(ContentLength))]),
			})
			_, err = conn.WriteToUDP(jsonBuf.Bytes(), rAddr)
			jsonBuf.Reset()
			if err != nil {
				log.Println(err)
				continue
			}
		}
	}
}
